package cn.turboinfo.fuyang.api.domain.admin.usecase.category;

import cn.turboinfo.fuyang.api.domain.common.service.category.CategoryService;
import cn.turboinfo.fuyang.api.domain.common.service.file.FileAttachmentService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.domain.web.component.file.FileRefTypeConstant;
import cn.turboinfo.fuyang.api.entity.common.pojo.category.Category;
import cn.turboinfo.fuyang.api.entity.common.pojo.file.FileAttachment;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QPage;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.response.QResponse;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class CategorySearchUseCase extends AbstractUseCase<CategorySearchUseCase.InputData, CategorySearchUseCase.OutputData> {
    private final CategoryService categoryService;

    private final FileAttachmentService fileAttachmentService;

    @Override
    protected OutputData doAction(InputData inputData) {

        QResponse<Category> response = categoryService.findAll(inputData.getRequest(), inputData.getRequestPage());

        Set<Long> categoryIdSet = response.getPagedData()
                .stream()
                .map(Category::getId)
                .collect(Collectors.toSet());

        Map<Long, FileAttachment> fileAttachmentMap = fileAttachmentService.findByRefIdInAndRefType(categoryIdSet, FileRefTypeConstant.CATEGORY_ICON)
                .stream()
                .collect(Collectors.toMap(FileAttachment::getRefId, o -> o, (o1, o2) -> o1));

        response.getPagedData().stream()
                .peek(category -> {
                    FileAttachment fileAttachment = fileAttachmentMap.get(category.getId());
                    if (fileAttachment != null) {
                        category.setIconId(fileAttachment.getId());
                    }
                })
                .toList();

        return OutputData.builder()
                .qResponse(response)
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        private QRequest request;

        private QPage requestPage;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private QResponse<Category> qResponse;
    }
}
